#!/usr/bin/env python3
"""
智能MCP系统客户端SDK
方便团队成员快速接入和使用MCP系统
"""

import requests
import json
from datetime import datetime
from typing import Dict, List, Any, Optional

class MCPClient:
    """智能MCP系统客户端"""
    
    def __init__(self, base_url: str = "http://127.0.0.1:8085"):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json',
            'User-Agent': 'MCP-Client/1.0'
        })
    
    def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            response = self.session.get(f"{self.base_url}/api/health")
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"status": "error", "message": str(e)}
    
    def process_llm_inference(self, llm_data: Dict[str, Any]) -> Dict[str, Any]:
        """处理LLM推理结果"""
        try:
            response = self.session.post(
                f"{self.base_url}/api/intelligent/process_llm_inference",
                json={"llm_data": llm_data}
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def auto_process_and_execute(self, llm_data: Dict[str, Any]) -> Dict[str, Any]:
        """自动处理并执行"""
        try:
            response = self.session.post(
                f"{self.base_url}/api/intelligent/auto_process_and_execute",
                json={"llm_data": llm_data}
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def generate_ansible_scripts(self, agent_results: List[Dict], 
                               kylin_config: Dict = None, 
                               target_hosts: str = "all") -> Dict[str, Any]:
        """生成Ansible脚本"""
        try:
            payload = {
                "agent_results": agent_results,
                "kylin_config": kylin_config or {"server": "localhost:8080"},
                "target_hosts": target_hosts
            }
            response = self.session.post(
                f"{self.base_url}/api/ansible/generate_scripts",
                json=payload
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def deploy_to_kylin(self, package_id: str, 
                       kylin_server: str = "localhost:8080",
                       kylin_credentials: Dict = None) -> Dict[str, Any]:
        """部署到Kylin"""
        try:
            payload = {
                "package_id": package_id,
                "kylin_server": kylin_server,
                "kylin_credentials": kylin_credentials or {}
            }
            response = self.session.post(
                f"{self.base_url}/api/ansible/deploy_to_kylin",
                json=payload
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def get_execution_history(self, limit: int = 10) -> Dict[str, Any]:
        """获取执行历史"""
        try:
            response = self.session.get(
                f"{self.base_url}/api/intelligent/execution_history",
                params={"limit": limit}
            )
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def analyze_problem_patterns(self) -> Dict[str, Any]:
        """分析问题模式"""
        try:
            response = self.session.get(f"{self.base_url}/api/intelligent/problem_patterns")
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def get_script_templates(self) -> Dict[str, Any]:
        """获取脚本模板"""
        try:
            response = self.session.get(f"{self.base_url}/api/ansible/script_templates")
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def list_tools(self) -> Dict[str, Any]:
        """列出所有工具"""
        try:
            response = self.session.get(f"{self.base_url}/api/tools")
            response.raise_for_status()
            return response.json()
        except Exception as e:
            return {"success": False, "error": str(e)}

# 便捷函数
def create_llm_data(problem_type: str, severity: float, description: str,
                   affected_services: List[str] = None,
                   suggested_actions: List[str] = None,
                   confidence: float = 0.8,
                   reasoning: str = "") -> Dict[str, Any]:
    """创建LLM数据"""
    return {
        "problem_type": problem_type,
        "severity": severity,
        "description": description,
        "affected_services": affected_services or [],
        "suggested_actions": suggested_actions or [],
        "confidence": confidence,
        "reasoning": reasoning,
        "timestamp": datetime.now().isoformat()
    }

def create_agent_result(agent_type: str, result: Dict[str, Any],
                       parameters: Dict[str, Any] = None) -> Dict[str, Any]:
    """创建Agent结果"""
    return {
        "agent_type": agent_type,
        "result": result,
        "parameters": parameters or {}
    }

# 使用示例
if __name__ == "__main__":
    # 创建客户端
    client = MCPClient()
    
    # 健康检查
    print("🔍 健康检查:")
    health = client.health_check()
    print(json.dumps(health, indent=2, ensure_ascii=False))
    
    # 创建LLM数据
    llm_data = create_llm_data(
        problem_type="cpu_high_usage",
        severity=8.0,
        description="CPU使用率异常高，可能影响系统性能",
        affected_services=["web-service", "database"],
        suggested_actions=["检查CPU密集型进程", "优化查询"],
        confidence=0.9,
        reasoning="CPU使用率超过90%，系统负载异常"
    )
    
    # 自动处理并执行
    print("\n🤖 自动处理并执行:")
    result = client.auto_process_and_execute(llm_data)
    print(json.dumps(result, indent=2, ensure_ascii=False))
    
    # 获取执行历史
    print("\n📊 执行历史:")
    history = client.get_execution_history(limit=5)
    print(json.dumps(history, indent=2, ensure_ascii=False))
    
    # 分析问题模式
    print("\n📈 问题模式分析:")
    patterns = client.analyze_problem_patterns()
    print(json.dumps(patterns, indent=2, ensure_ascii=False)) 